package com.studentmanagement.ui;

import com.studentmanagement.model.Course;
import com.studentmanagement.model.User;
import com.studentmanagement.service.CourseService;
import com.studentmanagement.service.EnrollmentService;
import com.studentmanagement.service.StudentService;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.util.List;

public class CourseSelectionPanel extends JPanel {
    private User currentUser;
    private CourseService courseService;
    private EnrollmentService enrollmentService;
    private StudentService studentService;
    
    private JTable courseTable;
    private DefaultTableModel tableModel;
    private JTextField searchField;
    private JTextField departmentField;
    private JButton searchButton;
    private JButton viewDetailButton;
    private JButton selectCourseButton;
    private JButton refreshButton;

    public CourseSelectionPanel(User user) {
        this.currentUser = user;
        this.courseService = new CourseService();
        this.enrollmentService = new EnrollmentService();
        this.studentService = new StudentService();
        
        initComponents();
        setupLayout();
        setupListeners();
        loadCourseData();
    }

    private void initComponents() {
        // 表格列名
        String[] columnNames = {"课程代码", "课程名称", "教师", "学分", "院系", "上课时间", "教室", "剩余容量"};
        tableModel = new DefaultTableModel(columnNames, 0) {
            @Override
            public boolean isCellEditable(int row, int column) {
                return false;
            }
        };
        
        courseTable = new JTable(tableModel);
        courseTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        courseTable.getTableHeader().setReorderingAllowed(false);
        courseTable.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        courseTable.getTableHeader().setFont(new Font("微软雅黑", Font.BOLD, 14));
        courseTable.setRowHeight(30);
        
        // 搜索字段初始化
        searchField = new JTextField(15);
        departmentField = new JTextField(15);
        
        // 按钮初始化
        searchButton = new JButton("搜索");
        viewDetailButton = new JButton("查看详情");
        selectCourseButton = new JButton("选课");
        refreshButton = new JButton("刷新");
        
        // 设置字体
        Font font = new Font("微软雅黑", Font.PLAIN, 14);
        searchField.setFont(font);
        departmentField.setFont(font);
        searchButton.setFont(font);
        viewDetailButton.setFont(font);
        selectCourseButton.setFont(font);
        refreshButton.setFont(font);
    }

    private void setupLayout() {
        setLayout(new BorderLayout(10, 10));
        setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));

        // 创建标题面板
        JPanel titlePanel = new JPanel();
        JLabel titleLabel = new JLabel("选课中心");
        titleLabel.setFont(new Font("微软雅黑", Font.BOLD, 24));
        titlePanel.add(titleLabel);

        // 创建搜索面板
        JPanel searchPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
        searchPanel.add(new JLabel("课程名称:"));
        searchPanel.add(searchField);
        searchPanel.add(new JLabel("开课院系:"));
        searchPanel.add(departmentField);
        searchPanel.add(searchButton);

        // 创建按钮面板
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
        buttonPanel.add(viewDetailButton);
        buttonPanel.add(selectCourseButton);
        buttonPanel.add(refreshButton);

        // 创建北部面板，包含标题、搜索和按钮
        JPanel northPanel = new JPanel(new BorderLayout());
        JPanel topPanel = new JPanel(new BorderLayout());
        topPanel.add(titlePanel, BorderLayout.WEST);
        topPanel.add(buttonPanel, BorderLayout.EAST);
        northPanel.add(topPanel, BorderLayout.NORTH);
        northPanel.add(searchPanel, BorderLayout.CENTER);

        // 添加组件到主面板
        add(northPanel, BorderLayout.NORTH);
        add(new JScrollPane(courseTable), BorderLayout.CENTER);
    }

    private void setupListeners() {
        searchButton.addActionListener(e -> searchCourses());
        viewDetailButton.addActionListener(e -> onViewDetail());
        selectCourseButton.addActionListener(e -> onSelectCourse());
        refreshButton.addActionListener(e -> loadCourseData());
    }

    private void loadCourseData() {
        tableModel.setRowCount(0);
        List<Course> courses = courseService.getAllCourses();
        
        for (Course course : courses) {
            // 获取已选人数
            int enrolledCount = enrollmentService.getEnrolledStudentCount(course.getId());
            int remainingCapacity = course.getCapacity() - enrolledCount;
            
            Object[] rowData = {
                course.getCourseCode(),
                course.getName(),
                course.getTeacherName() != null ? course.getTeacherName() : "未分配",
                course.getCredits(),
                course.getDepartment(),
                course.getSchedule(),
                course.getClassroom(),
                remainingCapacity + "/" + course.getCapacity()
            };
            tableModel.addRow(rowData);
        }
    }

    private void searchCourses() {
        String keyword = searchField.getText().trim();
        String department = departmentField.getText().trim();
        
        tableModel.setRowCount(0);
        List<Course> courses = courseService.searchCourses(keyword, department, null);
        
        for (Course course : courses) {
            int enrolledCount = enrollmentService.getEnrolledStudentCount(course.getId());
            int remainingCapacity = course.getCapacity() - enrolledCount;
            
            Object[] rowData = {
                course.getCourseCode(),
                course.getName(),
                course.getTeacherName() != null ? course.getTeacherName() : "未分配",
                course.getCredits(),
                course.getDepartment(),
                course.getSchedule(),
                course.getClassroom(),
                remainingCapacity + "/" + course.getCapacity()
            };
            tableModel.addRow(rowData);
        }
    }

    private void onViewDetail() {
        int selectedRow = courseTable.getSelectedRow();
        if (selectedRow == -1) {
            JOptionPane.showMessageDialog(this, "请先选择一门课程！", "提示", JOptionPane.INFORMATION_MESSAGE);
            return;
        }

        String courseCode = (String) tableModel.getValueAt(selectedRow, 0);
        Course course = courseService.getCourseByCourseCode(courseCode);
        
        if (course != null) {
            StringBuilder details = new StringBuilder();
            details.append("课程详情：\n\n");
            details.append("课程代码：").append(course.getCourseCode()).append("\n");
            details.append("课程名称：").append(course.getName()).append("\n");
            details.append("授课教师：").append(course.getTeacherName() != null ? course.getTeacherName() : "未分配").append("\n");
            details.append("开课院系：").append(course.getDepartment()).append("\n");
            details.append("学分：").append(course.getCredits()).append("\n");
            details.append("课程容量：").append(course.getCapacity()).append("\n");
            details.append("上课时间：").append(course.getSchedule()).append("\n");
            details.append("上课地点：").append(course.getClassroom()).append("\n");
            details.append("课程描述：").append(course.getDescription());

            JTextArea textArea = new JTextArea(details.toString());
            textArea.setEditable(false);
            textArea.setFont(new Font("微软雅黑", Font.PLAIN, 14));
            textArea.setLineWrap(true);
            textArea.setWrapStyleWord(true);
            
            JScrollPane scrollPane = new JScrollPane(textArea);
            scrollPane.setPreferredSize(new Dimension(400, 300));

            JOptionPane.showMessageDialog(this, scrollPane, "课程详情", JOptionPane.INFORMATION_MESSAGE);
        }
    }

    private void onSelectCourse() {
        int selectedRow = courseTable.getSelectedRow();
        if (selectedRow == -1) {
            JOptionPane.showMessageDialog(this, "请先选择一门课程！", "提示", JOptionPane.INFORMATION_MESSAGE);
            return;
        }

        String courseCode = (String) tableModel.getValueAt(selectedRow, 0);
        Course course = courseService.getCourseByCourseCode(courseCode);
        
        if (course != null) {
            // 检查课程容量
            int enrolledCount = enrollmentService.getEnrolledStudentCount(course.getId());
            if (enrolledCount >= course.getCapacity()) {
                JOptionPane.showMessageDialog(this, "该课程已满！", "提示", JOptionPane.WARNING_MESSAGE);
                return;
            }

            // 检查是否已选过该课程
            if (enrollmentService.isEnrolled(
                studentService.getStudentByUserId(currentUser.getId()).getId(),
                course.getId()
            )) {
                JOptionPane.showMessageDialog(this, "您已经选过该课程！", "提示", JOptionPane.WARNING_MESSAGE);
                return;
            }

            int confirm = JOptionPane.showConfirmDialog(this,
                "确定要选择该课程吗？",
                "确认选课",
                JOptionPane.YES_NO_OPTION);

            if (confirm == JOptionPane.YES_OPTION) {
                boolean success = enrollmentService.enrollCourse(
                    studentService.getStudentByUserId(currentUser.getId()).getId(),
                    course.getId()
                );

                if (success) {
                    JOptionPane.showMessageDialog(this, "选课成功！", "提示", JOptionPane.INFORMATION_MESSAGE);
                    loadCourseData(); // 刷新数据
                } else {
                    JOptionPane.showMessageDialog(this, "选课失败！", "错误", JOptionPane.ERROR_MESSAGE);
                }
            }
        }
    }
} 